package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.ObjectMapper;

import oracle.net.aso.p;
import po.Cart;
import po.Dish;
import service.CartService;
import service.impl.CartServiceImpl;

/**
 * Servlet implementation class ShowCartServlet
 */
public class ShowCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowCartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
    	response.setHeader("content-type","text/html;charset=UTF-8");
    	HttpSession session = request.getSession();
    	ObjectMapper mapper = new ObjectMapper();
    	
    	if(session.getAttribute("cId") != null){
    	int cId = (int)session.getAttribute("cId");
    	HashMap<Integer, Dish> dishMap = new HashMap<Integer,Dish>();
    	PrintWriter pWriter = response.getWriter();
    	
		CartService cartService = new CartServiceImpl();
		List<Dish> dishList = new ArrayList<Dish>();
		dishList = cartService.queryCart(cId);
		for(Dish d:dishList){			
			dishMap.put(d.getdId(),d);
		}
		String dishString = mapper.writeValueAsString(dishMap);
		pWriter.println(dishString);
		System.out.println(dishString);
    	}
		
	}

}
